<?php namespace App\Http\Services;

use App\Enterprise;
use App\EnterpriseAdmin;
use App\EnterpriseApply;
use App\Merchant;
use App\MerchantStaff;
use Auth;
use Blocktrail\CryptoJSAES\CryptoJSAES;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Cookie;
use App\User;

class MerchantManager
{
    public static function isLogin(Request $request = null,$front = 0)
    {
        if (!isset($_COOKIE['merchant_token'])) {
            if (is_null($request)) {
                return false;
            } else {
                $token = !is_null($request->header('Merchant-token')) ? $request->header('Merchant-token') : $request->get('merchant_token');
                if (!is_null($token)) {

                    $openid = false;
                    try {
                        $openid = CryptoJSAES::decrypt(str_replace(" ", "+", $token), env("AES_KEY"));
                    } catch (\Exception $e) {
                        return false;
                    }

                    if (!$openid)
                        return false;

                    $thatUser = User::whereIn('role',[2,3])->whereUserKey($openid)->first();
                    if(!$thatUser){
                        return false;
                    }

                    return $thatUser;
                } else {
                    return false;
                }
            }
        } else {
            $token = Cookie::get('merchant_token');

            if (!$token || is_null($token))
                return false;

            $openid = false;
            try {
                $openid = CryptoJSAES::decrypt(str_replace(" ", "+", $token), env("AES_KEY"));
            } catch (\Exception $e) {
                return false;
            }

            if (!$openid)
                return false;

            $thatUser = User::whereIn('role',[2,3])->whereUserKey($openid)->first();
            if(!$thatUser){
                return false;
            }

            return $thatUser;
        }
    }

    /**
     * 获取商家信息
     * @param int $user_id
     * @return Merchant|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     */
    public static function getMerchantInfoByUserId($user_id = 0){
        $enterpriseId = 0;

        $user = user::whereId($user_id)->first();
        if($user && $user->role == 2){
            //管理员
            $enterpriseAdmin = EnterpriseAdmin::whereUserId($user->id)->first();
            if($enterpriseAdmin){
                $enterpriseId = $enterpriseAdmin->enterprise_id;
            }
        }elseif($user && $user->role == 3){
            //员工
            $merchantStaff = MerchantStaff::whereUserId($user->id)->first();
            if($merchantStaff){
                $merchant = Merchant::whereId($merchantStaff->merchant_id)->whereReview(1)->first();
                if($merchant){
                    $enterpriseId = $merchant->enterprise_id;
                }
            }
        }

        $enterprise = Enterprise::whereId($enterpriseId)->whereStatus(1)->first();
        if(!$enterprise)
            return null;

        $merchant = Merchant::whereEnterpriseId($enterprise->id)->pluck('id')->toArray();

        $enterprise->merchant_id_arr = $merchant;

        return $enterprise;
    }

    public static function getMerchantAdminById($enterprise_id = 0){
        if(empty($enterprise_id))
            return [];

        $enterpriseAdmin = EnterpriseAdmin::whereEnterpriseId($enterprise_id)->pluck('user_id')->toArray();

        $merchantIds = Merchant::whereEnterpriseId($enterprise_id)->pluck('id');

        $enterpriseStaff = MerchantStaff::where('merchant_id',$merchantIds)->pluck('user_id')->toArray();

        $enterpriseUser = array_merge($enterpriseAdmin,$enterpriseStaff);

        return $enterpriseUser;
    }

    public static function buildUserKey($user_id = 0)
    {
        $num = mt_rand(1000, 9999);
        $rzKey = md5($user_id . time() . $num);
        return $rzKey;
    }

    public static function signUp($username, $password,$phone,$admin_name = '')
    {
        $user = new User();
        $user->username = $username;
        $user->admin_name = $admin_name;

        if(!empty($password))
            $user->password = bcrypt($password);

        $user->phone    = $phone;
        $user->reg_ip   = '';
        $user->reg_time = date("Y-m-d H:i:s",time());
        $user->role     = 2;
        $user->status   = 1;
        $user->save();

        $user->user_key = self::buildUserKey($user->id);
        $user->save();

        return $user;
    }

    /**
     * 检查用户名是否已经存在或被使用
     * @param $username
     * @return bool
     */
    public static function isUsernameExists($username){
        if(User::whereUsername($username)->exists())
            return true;
        return false;
    }

    /**
     * 通过用户名来登录
     * @param $username
     * @param $password
     * @param bool $remember
     * @return User|bool|null
     */
    public static function signInByUsername($username, $password, $remember = false){
        if(!self::isUsernameExists($username))
            return false;

        if(Auth::attempt(['username' => $username, 'password' => $password],$remember)){
            return Auth::user();
        }

        return false;
    }
}
